package com.shuda.business.engine.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shuda.business.data.entity.ScriptConfigEntity;
import com.shuda.business.data.dto.DataProcessingEngineDTO;
import com.shuda.business.external.dto.FormSubmitRequest;
import com.shuda.business.external.entity.ExternalFormRecordEntity;
import com.shuda.business.external.dto.DistributionResult;
import com.shuda.business.engine.service.EngineService;
import com.shuda.business.engine.entity.*;
import com.shuda.business.engine.dto.*;
import com.shuda.common.core.domain.PageDTO;
import com.shuda.common.core.domain.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 数据处理引擎控制器
 */
@RestController
@RequestMapping("/api/engine")
@Tag(name = "数据处理引擎", description = "数据处理引擎管理接口")
public class EngineController {

    @Autowired
    private EngineService engineService;

    /**
     * 数据池相关接口
     */
    @GetMapping("/data-pool/list")
    @Operation(summary = "获取数据池列表")
    @PreAuthorize("hasAuthority('engine:data-pool:view')")
    public R<IPage<DataPoolEntity>> getDataPoolList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "数据池名称") @RequestParam(required = false) String poolName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        return R.ok(engineService.getDataPoolList(pageNum, pageSize, poolName, status));
    }

    @GetMapping("/data-pool/{id}")
    @Operation(summary = "获取数据池详情")
    @PreAuthorize("hasAuthority('engine:data-pool:view')")
    public R<DataPoolEntity> getDataPoolById(@Parameter(description = "数据池ID") @PathVariable Long id) {
        return R.ok(engineService.getDataPoolById(id));
    }

    @PostMapping("/data-pool")
    @Operation(summary = "创建数据池")
    @PreAuthorize("hasAuthority('engine:data-pool:create')")
    public R<Boolean> createDataPool(@Valid @RequestBody DataPoolDTO poolDTO) {
        return R.ok(engineService.createDataPool(poolDTO));
    }

    @PutMapping("/data-pool/{id}")
    @Operation(summary = "更新数据池")
    @PreAuthorize("hasAuthority('engine:data-pool:update')")
    public R<Boolean> updateDataPool(
            @Parameter(description = "数据池ID") @PathVariable Long id,
            @Valid @RequestBody DataPoolDTO poolDTO) {
        return R.ok(engineService.updateDataPool(id, poolDTO));
    }

    @DeleteMapping("/data-pool/{id}")
    @Operation(summary = "删除数据池")
    @PreAuthorize("hasAuthority('engine:data-pool:delete')")
    public R<Boolean> deleteDataPool(@Parameter(description = "数据池ID") @PathVariable Long id) {
        return R.ok(engineService.deleteDataPool(id));
    }

    @PutMapping("/data-pool/{id}/status")
    @Operation(summary = "更新数据池状态")
    @PreAuthorize("hasAuthority('engine:data-pool:update')")
    public R<Boolean> updateDataPoolStatus(
            @Parameter(description = "数据池ID") @PathVariable Long id,
            @Parameter(description = "状态") @RequestParam Integer status) {
        return R.ok(engineService.updateDataPoolStatus(id, status));
    }

    /**
     * 字段映射相关接口
     */
    @GetMapping("/field-mapping/list")
    @Operation(summary = "获取字段映射列表")
    @PreAuthorize("hasAuthority('engine:field-mapping:view')")
    public R<IPage<FieldMappingEntity>> getFieldMappingList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "映射名称") @RequestParam(required = false) String mappingName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        return R.ok(engineService.getFieldMappingList(pageNum, pageSize, mappingName, status));
    }

    @GetMapping("/field-mapping/{id}")
    @Operation(summary = "获取字段映射详情")
    @PreAuthorize("hasAuthority('engine:field-mapping:view')")
    public R<FieldMappingEntity> getFieldMappingById(@Parameter(description = "映射ID") @PathVariable Long id) {
        return R.ok(engineService.getFieldMappingById(id));
    }

    @PostMapping("/field-mapping")
    @Operation(summary = "创建字段映射")
    @PreAuthorize("hasAuthority('engine:field-mapping:create')")
    public R<Boolean> createFieldMapping(@Valid @RequestBody FieldMappingDTO mappingDTO) {
        return R.ok(engineService.createFieldMapping(mappingDTO));
    }

    @PutMapping("/field-mapping/{id}")
    @Operation(summary = "更新字段映射")
    @PreAuthorize("hasAuthority('engine:field-mapping:update')")
    public R<Boolean> updateFieldMapping(
            @Parameter(description = "映射ID") @PathVariable Long id,
            @RequestBody FieldMappingDTO mappingDTO) {
        return R.ok(engineService.updateFieldMapping(id, mappingDTO));
    }

    @DeleteMapping("/field-mapping/{id}")
    @Operation(summary = "删除字段映射")
    @PreAuthorize("hasAuthority('engine:field-mapping:delete')")
    public R<Boolean> deleteFieldMapping(@Parameter(description = "映射ID") @PathVariable Long id) {
        return R.ok(engineService.deleteFieldMapping(id));
    }

    @PutMapping("/field-mapping/{id}/status")
    @Operation(summary = "更新字段映射状态")
    @PreAuthorize("hasAuthority('engine:field-mapping:update')")
    public R<Boolean> updateFieldMappingStatus(
            @Parameter(description = "映射ID") @PathVariable Long id,
            @Parameter(description = "状态") @RequestParam Integer status) {
        return R.ok(engineService.updateFieldMappingStatus(id, status));
    }

    /**
     * 撞库检测相关接口
     */
    @GetMapping("/collision-check/list")
    @Operation(summary = "获取撞库检测配置列表")
    @PreAuthorize("hasAuthority('engine:collision-check:view')")
    public R<IPage<CollisionCheckEntity>> getCollisionCheckList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "配置名称") @RequestParam(required = false) String configName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        return R.ok(engineService.getCollisionCheckList(pageNum, pageSize, configName, status));
    }

    @GetMapping("/collision-check/{id}")
    @Operation(summary = "获取撞库检测配置详情")
    @PreAuthorize("hasAuthority('engine:collision-check:view')")
    public R<CollisionCheckEntity> getCollisionCheckById(@Parameter(description = "配置ID") @PathVariable Long id) {
        return R.ok(engineService.getCollisionCheckById(id));
    }

    @PostMapping("/collision-check")
    @Operation(summary = "创建撞库检测配置")
    @PreAuthorize("hasAuthority('engine:collision-check:create')")
    public R<Boolean> createCollisionCheck(@RequestBody CollisionCheckDTO checkDTO) {
        return R.ok(engineService.createCollisionCheck(checkDTO));
    }

    @PutMapping("/collision-check/{id}")
    @Operation(summary = "更新撞库检测配置")
    @PreAuthorize("hasAuthority('engine:collision-check:update')")
    public R<Boolean> updateCollisionCheck(
            @Parameter(description = "配置ID") @PathVariable Long id,
            @RequestBody CollisionCheckDTO checkDTO) {
        return R.ok(engineService.updateCollisionCheck(id, checkDTO));
    }

    @DeleteMapping("/collision-check/{id}")
    @Operation(summary = "删除撞库检测配置")
    @PreAuthorize("hasAuthority('engine:collision-check:delete')")
    public R<Boolean> deleteCollisionCheck(@Parameter(description = "配置ID") @PathVariable Long id) {
        return R.ok(engineService.deleteCollisionCheck(id));
    }

    @PutMapping("/collision-check/{id}/status")
    @Operation(summary = "更新撞库检测配置状态")
    @PreAuthorize("hasAuthority('engine:collision-check:update')")
    public R<Boolean> updateCollisionCheckStatus(
            @Parameter(description = "配置ID") @PathVariable Long id,
            @Parameter(description = "状态") @RequestParam Integer status) {
        return R.ok(engineService.updateCollisionCheckStatus(id, status));
    }

    /**
     * 脚本配置相关接口
     */
    @GetMapping("/script-config/list")
    @Operation(summary = "获取脚本配置列表")
    @PreAuthorize("hasAuthority('engine:script-config:view')")
    public R<IPage<ScriptConfigEntity>> getScriptConfigList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "脚本名称") @RequestParam(required = false) String scriptName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        return R.ok(engineService.getScriptConfigList(pageNum, pageSize, scriptName, status));
    }

    @GetMapping("/script-config/{id}")
    @Operation(summary = "获取脚本配置详情")
    @PreAuthorize("hasAuthority('engine:script-config:view')")
    public R<ScriptConfigEntity> getScriptConfigById(@Parameter(description = "配置ID") @PathVariable Long id) {
        return R.ok(engineService.getScriptConfigById(id));
    }

    @PostMapping("/script-config")
    @Operation(summary = "创建脚本配置")
    @PreAuthorize("hasAuthority('engine:script-config:create')")
    public R<Boolean> createScriptConfig(@RequestBody DataProcessingEngineDTO configDTO) {
        return R.ok(engineService.createScriptConfig(configDTO));
    }

    @PutMapping("/script-config/{id}")
    @Operation(summary = "更新脚本配置")
    @PreAuthorize("hasAuthority('engine:script-config:update')")
    public R<Boolean> updateScriptConfig(
            @Parameter(description = "配置ID") @PathVariable Long id,
            @RequestBody DataProcessingEngineDTO configDTO) {
        return R.ok(engineService.updateScriptConfig(id, configDTO));
    }

    @DeleteMapping("/script-config/{id}")
    @Operation(summary = "删除脚本配置")
    @PreAuthorize("hasAuthority('engine:script-config:delete')")
    public R<Boolean> deleteScriptConfig(@Parameter(description = "配置ID") @PathVariable Long id) {
        return R.ok(engineService.deleteScriptConfig(id));
    }

    @PutMapping("/script-config/{id}/status")
    @Operation(summary = "更新脚本配置状态")
    @PreAuthorize("hasAuthority('engine:script-config:update')")
    public R<Boolean> updateScriptConfigStatus(
            @Parameter(description = "配置ID") @PathVariable Long id,
            @Parameter(description = "状态") @RequestParam Integer status) {
        return R.ok(engineService.updateScriptConfigStatus(id, status));
    }

    /**
     * 验证规则相关接口
     */
    @GetMapping("/validation-rule/list")
    @Operation(summary = "获取验证规则列表")
    @PreAuthorize("hasAuthority('engine:validation-rule:view')")
    public R<IPage<ValidationRuleEntity>> getValidationRuleList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "规则名称") @RequestParam(required = false) String ruleName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        return R.ok(engineService.getValidationRuleList(pageNum, pageSize, ruleName, status));
    }

    @GetMapping("/validation-rule/{id}")
    @Operation(summary = "获取验证规则详情")
    @PreAuthorize("hasAuthority('engine:validation-rule:view')")
    public R<ValidationRuleEntity> getValidationRuleById(@Parameter(description = "规则ID") @PathVariable Long id) {
        return R.ok(engineService.getValidationRuleById(id));
    }

    @PostMapping("/validation-rule")
    @Operation(summary = "创建验证规则")
    @PreAuthorize("hasAuthority('engine:validation-rule:create')")
    public R<Boolean> createValidationRule(@RequestBody ValidationRuleDTO ruleDTO) {
        return R.ok(engineService.createValidationRule(ruleDTO));
    }

    @PutMapping("/validation-rule/{id}")
    @Operation(summary = "更新验证规则")
    @PreAuthorize("hasAuthority('engine:validation-rule:update')")
    public R<Boolean> updateValidationRule(
            @Parameter(description = "规则ID") @PathVariable Long id,
            @RequestBody ValidationRuleDTO ruleDTO) {
        return R.ok(engineService.updateValidationRule(id, ruleDTO));
    }

    @DeleteMapping("/validation-rule/{id}")
    @Operation(summary = "删除验证规则")
    @PreAuthorize("hasAuthority('engine:validation-rule:delete')")
    public R<Boolean> deleteValidationRule(@Parameter(description = "规则ID") @PathVariable Long id) {
        return R.ok(engineService.deleteValidationRule(id));
    }

    @PutMapping("/validation-rule/{id}/status")
    @Operation(summary = "更新验证规则状态")
    @PreAuthorize("hasAuthority('engine:validation-rule:update')")
    public R<Boolean> updateValidationRuleStatus(
            @Parameter(description = "规则ID") @PathVariable Long id,
            @Parameter(description = "状态") @RequestParam Integer status) {
        return R.ok(engineService.updateValidationRuleStatus(id, status));
    }

    /**
     * 引擎执行相关接口
     */
    @PostMapping("/execute")
    @Operation(summary = "执行数据处理引擎")
    @PreAuthorize("hasAuthority('engine:execute')")
    public R<Boolean> executeEngine(@RequestBody FormSubmitRequest executionDTO) {
        return R.ok(engineService.executeEngine(executionDTO));
    }

    @GetMapping("/status")
    @Operation(summary = "获取引擎状态")
    @PreAuthorize("hasAuthority('engine:view')")
    public R<EngineStatusEntity> getEngineStatus() {
        return R.ok(engineService.getEngineStatus());
    }
}